package com.moss.cloud.auth.biz.filter;

import com.alibaba.fastjson2.JSON;
import com.moss.cloud.auth.biz.utils.HeaderMapRequestWrapper;
import com.moss.cloud.auth.biz.utils.ParameterRequestWrapper;
import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.exception.SystemErrorType;
import com.moss.cloud.common.core.model.Result;
import com.moss.cloud.common.core.utils.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 密码解密处理过滤器，解密前端AES加密的密码，
 * AES加密算法需优化
 * @author 瑾年
 * @data 2023年3月8日
 */
@Component
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class PassWordFilter extends GenericFilterBean {
    private static final String OAUTH_TOKEN_URL="/oauth/token";
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if(OAUTH_TOKEN_URL.equals(request.getRequestURI())){
            try{
                String password = servletRequest.getParameter("password");
                password = AESUtil.aesDecrypt(password, Constant.KEY);
                //重写HttpServletRequestWrapper
                HeaderMapRequestWrapper requestWrapper = getHeaderMapRequestWrapper(request,password);
                filterChain.doFilter(requestWrapper,response);
            }catch (Exception e){
                log.error("密码解密异常:{}",e.getMessage());
                Result result = Result.fail(SystemErrorType.INVALID_GRANT, "");
                String jsonString = JSON.toJSONString(result);
                ServletOutputStream outputStream = response.getOutputStream();
                outputStream.write(jsonString.getBytes());
                outputStream.flush();
            }
        }else{
            filterChain.doFilter(request,response);
        }
    }
    /**
     * 重建请求，
     * @param request      request
     * @param password     password
     * @return HeaderMapRequestWrapper
     */
    private HeaderMapRequestWrapper getHeaderMapRequestWrapper(HttpServletRequest request,
                                                               String password) {
        //切记一定要new HashMap,不然不能被修改
        Map<String, String[]> map = new HashMap<>(request.getParameterMap());
        map.remove("password");
        map.put("password", new String[]{password});
        ParameterRequestWrapper wrapRequest = new ParameterRequestWrapper(request, map);
        HeaderMapRequestWrapper requestHeaderWrapper = new HeaderMapRequestWrapper(wrapRequest);
        return requestHeaderWrapper;
    }
}
